package org.backend.canteenbackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.backend.canteenbackend.common.CommonResponse;
import org.backend.canteenbackend.entity.*;
import org.backend.canteenbackend.persistence.*;
import org.backend.canteenbackend.service.CatalogService;
import org.backend.canteenbackend.vo.CategoryVO;
import org.backend.canteenbackend.vo.ItemVO;
import org.backend.canteenbackend.vo.ProductVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;

@Service("catalogService")
public class CatalogServiceImpl implements CatalogService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private ItemQuantityMapper itemQuantityMapper;
    @Autowired
    private LanguagesMapper languagesMapper;
    @Autowired
    private ProfileMapper profileMapper;


    //查询单个类及其商品列表
    @Override
    public CommonResponse<CategoryVO> getCategory(String categoryId){
        Category category = categoryMapper.selectById(categoryId);
        if(category == null){
            return CommonResponse.createForSuccessMessage("Category not found");
        }
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        // 只查询 id 和 name 字段
        queryWrapper.select("productid", "name").eq("category", categoryId);
        List<Map<String, Object>> productMaps = productMapper.selectMaps(queryWrapper);
        CategoryVO categoryVO = convertToCategoryVO(category, productMaps);

        return CommonResponse.createForSuccess( categoryVO );
    }

    @Override
    public CommonResponse<ProductVO> getProduct(String productId){
        Product product = productMapper.selectById(productId);
        if(product == null){
            return CommonResponse.createForSuccessMessage("Product not found");
        }
        //查所属category
        Category category = categoryMapper.selectById(product.getCategoryId());
        if (category == null) {
            return CommonResponse.createForError("产品分类不存在");
        }
        //查item
        QueryWrapper<Item> itemQuery = new QueryWrapper<>();
        itemQuery.eq("productid", productId);
        Item item = itemMapper.selectOne(itemQuery);
        if (item == null) {
            return CommonResponse.createForError("产品明细不存在");
        }

        ProductVO productVO = convertToProductVO(category, product,item);
        return CommonResponse.createForSuccess( productVO );
    }

    @Override
    public CommonResponse<ItemVO> getItem(String productId) {
        // 查 Product
        Product product = productMapper.selectById(productId);
        if (product == null) {
            return CommonResponse.createForError("产品不存在");
        }

        // 查所属 Category
        Category category = categoryMapper.selectById(product.getCategoryId());
        if (category == null) {
            return CommonResponse.createForError("产品分类不存在");
        }

        // 查 Item（通过 productId 查询对应的 item）
        QueryWrapper<Item> itemQuery = new QueryWrapper<>();
        itemQuery.eq("productid", productId);
        Item item = itemMapper.selectOne(itemQuery);
        if (item == null) {
            return CommonResponse.createForError("产品明细不存在");
        }

        ItemVO itemVO = convertToItemVO(item, product);
        return CommonResponse.createForSuccess(itemVO);
    }

    @Override
    public List<Languages> getAllLanguages(){
        QueryWrapper<Languages> queryWrapper = new QueryWrapper<>();
        return languagesMapper.selectList(queryWrapper);
    }
    @Override
    public boolean updateUserLanguage(String userId, String language){
        if (userId == null || language == null || language.isEmpty()) {
            return false;
        }

        int rows = profileMapper.updateUserLanguage(userId, language);
        return rows > 0;
    }

    @Override
    public List<Product> searchProductList(String keyword) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        if (keyword != null && !keyword.trim().isEmpty()) {
            queryWrapper.like("name", keyword);
        }
        return productMapper.selectList(queryWrapper);
    }


    private CategoryVO convertToCategoryVO(Category category, List<Map<String, Object>> productMaps){
        CategoryVO categoryVO = new CategoryVO();
        categoryVO.setCategoryId(category.getCategoryId());
        categoryVO.setCategoryName(category.getName());

        categoryVO.setProductList(productMaps);
        return categoryVO;
    }

    private ProductVO convertToProductVO(Category category, Product product, Item item){
        ProductVO productVO = new ProductVO();
        productVO.setCategoryId(category.getCategoryId());
        productVO.setCategoryName(category.getName());

        productVO.setProductId(product.getProductId());
        productVO.setProductName(product.getName());

        productVO.setItemId(item.getItemId());
        productVO.setListPrice(item.getListPrice());
        productVO.setAttribute1(item.getAttribute1());
        productVO.setAttribute2(item.getAttribute2());
        productVO.setAttribute3(item.getAttribute3());
        productVO.setAttribute4(item.getAttribute4());
        productVO.setAttribute5(item.getAttribute5());

        return productVO;
    }

    private ItemVO convertToItemVO(Item item,Product product){
        ItemVO itemVO = new ItemVO();

        itemVO.setItemId(item.getItemId());
        itemVO.setProductId(product.getProductId());
        itemVO.setListPrice(item.getListPrice());
        itemVO.setUnitCost(item.getUnitCost());
        itemVO.setSupplierId(item.getSupplierId());
        itemVO.setStatus(item.getStatus());
        itemVO.setAttribute1(item.getAttribute1());
        itemVO.setAttribute2(item.getAttribute2());
        itemVO.setAttribute3(item.getAttribute3());
        itemVO.setAttribute4(item.getAttribute4());
        itemVO.setAttribute5(item.getAttribute5());

        itemVO.setCategoryId(product.getCategoryId());
        itemVO.setProductName(product.getName());
        itemVO.setProductDescription(product.getDescription());

        ItemQuantity itemQuantity = itemQuantityMapper.selectById(item.getItemId());
        itemVO.setQuantity(itemQuantity.getQuantity());

        return itemVO;
    }
}
